﻿namespace HynuIOTA.Helpers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text;

    public static class AESEncryptionHelper
    {
        public static string AESEncrypt(string encryptStr, string key)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key);
            byte[] encryptBytes = Encoding.UTF8.GetBytes(encryptStr);

            RijndaelManaged RM = new RijndaelManaged();

            RM.KeySize = 256;
            RM.BlockSize = 256;
            RM.FeedbackSize = 256;
            RM.Mode = CipherMode.CBC;
            RM.Padding = PaddingMode.PKCS7;
            RM.Key = (new SHA256Managed()).ComputeHash(keyBytes);
            RM.IV = (new SHA256Managed()).ComputeHash(keyBytes);

            ICryptoTransform cTransform = RM.CreateEncryptor();
            byte[] resultBytes = cTransform.TransformFinalBlock(encryptBytes, 0, encryptBytes.Length);

            return Convert.ToBase64String(resultBytes, Base64FormattingOptions.None);
        }

        public static string AESDencrypt(string dencryptStr,string key)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key);
            byte[] decryptBytes = Convert.FromBase64String(dencryptStr);

            RijndaelManaged RM = new RijndaelManaged();

            RM.KeySize = 256;
            RM.BlockSize = 256;
            RM.FeedbackSize = 256;
            RM.Mode = CipherMode.CBC;
            RM.Padding = PaddingMode.PKCS7;
            RM.Key = (new SHA256Managed()).ComputeHash(keyBytes);
            RM.IV = (new SHA256Managed()).ComputeHash(keyBytes);

            ICryptoTransform cTransform = RM.CreateDecryptor();
            byte[] resultBytes = cTransform.TransformFinalBlock(decryptBytes,0,decryptBytes.Length);

            return Encoding.UTF8.GetString(resultBytes);
        }
    }
}
